package cn.com.dbappsecurity.frame.request;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * request对象的包转  处理中文乱码的问题
 * @author dhz
 */
public class EncodingRequest extends HttpServletRequestWrapper{

	public static final Logger LOG = Logger.getLogger(EncodingRequest.class);
	private String uri_encoding;

	public EncodingRequest(HttpServletRequest request,String encoding) {
		super(request);
		this.uri_encoding = encoding;
	}
	
	@Override
	public String getParameter(String paramName) {
		String value = super.getParameter(paramName);
		return decodeParamValue(value);
	}

	@Override
	public String[] getParameterValues(String arg0){
		String[] values = super.getParameterValues(arg0);
		if(values != null){
			for(int i=0;i<values.length;i++){
				values[i] = decodeParamValue(values[i]);
			}
		}
		return values;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String,String[]> getParameterMap(){
		//获取参数
		Map<String,String[]> params = super.getParameterMap();
		for(String[] values : params.values()){
			for(int i=0;i<values.length;i++){
				values[i] = decodeParamValue(values[i]);
			}
		}
		return params;
	}
	
	/*
	 * 参数转码
	 * @param value
	 * @return
	 */
	private String decodeParamValue(String value){
		if (StringUtils.isBlank(value) || StringUtils.isBlank(uri_encoding)
				|| StringUtils.isNumeric(value)){
			return value;
		}else{
			try {
				return new String(value.getBytes("ISO8859_1"),uri_encoding);
			} catch (UnsupportedEncodingException e) {
				LOG.error("参数转码错误",e);
			}
		}
		return value;
	}
	
}
